package com.testshiro.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.testshiro.entity.SysAutho;
import com.testshiro.service.SysAccountService;

public class CustomRealm extends AuthorizingRealm {
	private final static Logger log = Logger.getLogger(CustomRealm.class);
	@Resource
	private SysAccountService sysaccountService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		log.info("getAuthoCheck");
		String username = (String) arg0.fromRealm(getName()).iterator().next();
		if (username != null) {
			List<SysAutho> pers = sysaccountService
					.getAuthosByUserName(username);
			if (pers != null && !pers.isEmpty()) {
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				for (SysAutho each : pers) {
					// 将权限资源添加到用户信息中
					info.addStringPermission(each.getMark());
				}
				return info;
			}
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		if (token != null) {
			return new SimpleAuthenticationInfo(token.getUsername(),
					token.getPassword(), getName());
		} else {
			return null;
		}

	}

}
